<?php

namespace app\controllers;


require_once("../oauth/qq/API/qqConnectAPI.php");

use app\events\UserLoginEvent;
use app\models\CCPRestSDK;
use app\models\UploadForm;
use app\models\UserForm;
use app\models\LoginForm;
use app\models\UserQueryForm;
use PHPExcel;
use PHPExcel_IOFactory;
use Yii;
use app\models\User;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{

    const EVENT_USER_LOGIN = 'phone';

    public function init()
    {
        parent::init(); // TODO"=>Change the autogenerated stub

        $this->on(self::EVENT_USER_LOGIN, ['app\models\OLog', 'add']);
        $this->on(self::EVENT_USER_LOGIN, ['app\models\Admin', 'sendMail']);
        $this->on(self::EVENT_USER_LOGIN, ['app\models\Friend', 'notifyFirend']);

    }

    public $enableCsrfValidation = false;

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    protected function checkLogin()
    {
        $token = Yii::$app->request->get('token');
        if (empty($token)) {
            return false;
        }

        $cacheToken = Yii::$app->cache->get($token);

        if (empty($cacheToken)) {

            return false;
        }

        $this->setToken($token);

        return true;

    }

    private function setToken($token)
    {
        Yii::$app->cache->set($token, ['isLogin' => 1], 10);
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (!Yii::$app->request->isGet) {
            return $this->json(1000, '请求失败', "is post");
        }

        if (!$this->checkLogin()) {
            return $this->json(1000, '请求失败');
        }

        $form = new UserQueryForm();
        $form->setAttributes(Yii::$app->request->get());

        if (!$form->validate()) {

            return $this->json(1000, '请求失败', $form->getErrors());
        }

        $list = User::find()->where(['email' => $form])->asArray()->all();

        return $this->json(0, '请求成功', $list);

    }

    /**
     * Displays a single User model.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        if (!Yii::$app->request->isPost) {
            return $this->json(1000, '请求失败', "is post");
        }

        if (!$this->checkLogin()) {
            return $this->json(1000, '请求失败', "token timeout");
        }

        $model = new User();
        $model->setAttributes(Yii::$app->request->post());
        if (!$model->validate()) {
            return $this->json(1000, '请求失败', $model->getErrors());

        }

        $model->password = md5($model->password);
        $model->save();
        return $this->json(0, '请求成功', $model->id);


    }


    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionRegister()
    {
        $form = new UserForm();

        if ($form->load(Yii::$app->request->post()) && $form->validate()) {


            $model = new User();
            $model->email = $form->email;
            $model->password = $form->getMD5Password();
            $model->save();

            return $this->redirect(array('/user/login'));
        } else {
            // 无论是初始化显示还是数据验证错误
            return $this->render('register', [
                'model' => $form,
            ]);
        }


    }


    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionLogin()
    {
        if (!Yii::$app->request->isPost) {
            return $this->json(1000, '请求失败', "is post");
        }

        $form = new LoginForm();

        $form->setAttributes(Yii::$app->request->post());

        if (!$form->validate()) {

            return $this->json(1000, '请求失败', $form->getErrors());

        }


        $res = User::find()->asArray()->where(
            ['email' => $form->email,
                'password' => md5($form->password),
            ]
        )->one();

        if (empty($res)) {
            return $this->json(1000, '请求失败', "账户密码错误");
        }

        $token = md5(time() . rand(1000, 9999));

        $this->setToken($token);

        return $this->json(1000, '请求成功', $token);

    }

    public function actionSend()
    {
        $email = $_GET['email'];

        $code = rand(100000, 999999);
        echo $code;

        \Yii::$app->cache->set($email, $code);
    }

    public function actionMail()
    {

        $mail = Yii::$app->mailer->compose();
        $mail->setTo('2236908854@qq.com');
        $mail->setSubject("邮件测试");
//$mail->setTextBody('zheshisha ');   //发布纯文字文本
        $mail->setHtmlBody("<br>问我我我我我");    //发布可以带html标签的文本
        if ($mail->send())
            echo "success";
        else
            echo "failse";
        die();
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionAuth()
    {

        $qc = new \QC();
        $qc->qq_login();
    }

    public function actionCallback()
    {

        $qq = new \QC();
        $access_token = $qq->qq_callback();
        $openid = $qq->get_openid();
        $q = new \QC($access_token, $openid);
        $data = $q->get_user_info();

        print_r($data);

    }

    public function actionQinfo()
    {
        $qc = new \QC();
        $openid = $qc->get_openid();

        print_r($qc->get_info());
    }


    public function actionUpload()
    {

        $model = new UploadForm();

        if (Yii::$app->request->isPost) {
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
            $filePath = $model->upload();

            if($filePath){

                $objPHPExcelReader = PHPExcel_IOFactory::load($filePath);

                $sheet = $objPHPExcelReader->getSheet(0);        // 读取第一个工作表(编号从 0 开始)
                $highestRow = $sheet->getHighestRow();           // 取得总行数
                $highestColumn = $sheet->getHighestColumn();     // 取得总列数

                $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
                // 一次读取一列
                $res_arr = array();
                for ($row = 2; $row <= $highestRow; $row++) {
                    $row_arr = array();
                    for ($column = 0; $arr[$column] != 'F'; $column++) {
                        $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                        $row_arr[] = $val;
                    }

                    $res_arr[] = $row_arr;
                }


                $model = new User();
                foreach($res_arr as $attributes)
                {
                    $_model = clone $model;
                    $_model->setAttributes($attributes);
                    $_model->save();
                }

            }


        }

        return $this->render('upload', ['model' => $model]);
    }

    public function actionDown()
    {

        return $this->render("down");
    }

    public function actionPhone()
    {


//        $event = new UserLoginEvent();
//        $event->userId = 11;
//
//        $this->trigger(self::EVENT_USER_LOGIN,$event);

        $rest = CCPRestSDK::init();

        $isSuccess = $rest->sendSMS("18688725574", ["111", "30"]);

        if (!$isSuccess) {
            return "send fail";
        }

        return "send success";


    }


    public function actionExcel()
    {

        $user = User::find()->asArray()->all();
        $firstRow = ['id','email','password','created'];

        array_unshift($user,$firstRow);

        $objPHPExcel = new PHPExcel();

        $row = 1;
        foreach ($user as $rowData){
            $column = 0;
            foreach ($rowData as  $columnValue){

                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($column, $row,$columnValue);
                $column++;
            }

            $row++;
        }

        header('Content-Type"=>application/vnd.ms-excel');
        header('Content-Disposition"=>attachment;filename="abc.xls"');

        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter->save('php://output');

    }


    public function actionIn(){


        $filename = dirname(__FILE__).'/abc.xls';


        $objPHPExcelReader = PHPExcel_IOFactory::load($filename);

        $sheet = $objPHPExcelReader->getSheet(0);        // 读取第一个工作表(编号从 0 开始)
        $highestRow = $sheet->getHighestRow();           // 取得总行数
        $highestColumn = $sheet->getHighestColumn();     // 取得总列数

        $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        // 一次读取一列
        $res_arr = array();
        for ($row = 2; $row <= $highestRow; $row++) {
            $row_arr = array();
            for ($column = 0; $arr[$column] != 'F'; $column++) {
                $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                $row_arr[] = $val;
            }

            $res_arr[] = $row_arr;
        }

        return $this->json(0,"请求成功",$res_arr);
    }


    public function actionHigh(){



        $result = [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175];
        $data = [[
            "name"=>'每天创建人数',
            "data"=>$result
        ]];
        return $this->render('high_chart',['data' => $data]);
    }

}
